﻿using System;
using System.Timers;
using Timer= System.Timers.Timer;
public class Clock : IDisposable
{
    private readonly Timer _timer;
    private TimeSpan _alarmTime;
    private bool _alarmTriggered;

    public event EventHandler Tick;
    public event EventHandler Alarm;

    public Clock()
    {
        _timer = new Timer(1000); // 1秒间隔
        _timer.Elapsed += OnTimedEvent;
        _timer.AutoReset = true;
    }

    public void SetAlarm(TimeSpan alarmTime)
    {
        if (alarmTime.TotalHours >= 24 || alarmTime < TimeSpan.Zero)
            throw new ArgumentException("无效时间格式 (使用HH:mm:ss)");

        _alarmTime = alarmTime;
        _alarmTriggered = false;
    }

    public void Start() => _timer.Start();
    public void Stop() => _timer.Stop();

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        Tick?.Invoke(this, EventArgs.Empty); // 触发滴答事件

        var currentTime = DateTime.Now.TimeOfDay;
        if (!_alarmTriggered && currentTime >= _alarmTime)
        {
            _alarmTriggered = true;
            Alarm?.Invoke(this, EventArgs.Empty); // 触发响铃事件
            Stop();
        }
    }

    public void Dispose() => _timer.Dispose();
}

// 使用示例
class Program
{
    static void Main()
    {
        using var clock = new Clock();

        Console.WriteLine("输入闹钟时间 (HH:mm:ss): ");
        if (!TimeSpan.TryParse(Console.ReadLine(), out var alarmTime))
        {
            Console.WriteLine("时间格式错误！");
            return;
        }

        clock.SetAlarm(alarmTime);
        clock.Tick += (s, e) => Console.WriteLine($"[滴答] 当前时间: {DateTime.Now:T}");
        clock.Alarm += (s, e) => Console.WriteLine("⏰ 叮铃铃！！！该起床啦！");

        clock.Start();
        Console.WriteLine("按任意键退出...");
        Console.ReadKey();
    }
}